package com.xique.system.controller;

import com.sun.org.apache.bcel.internal.generic.I2F;
import com.xique.common.core.constant.UserConstants;
import com.xique.common.core.utils.SecurityUtils;
import com.xique.common.core.web.controller.BaseController;
import com.xique.common.core.web.domain.AjaxResult;
import com.xique.common.core.web.page.TableDataInfo;
import com.xique.common.log.annotation.Log;
import com.xique.common.log.enums.BusinessType;
import com.xique.common.security.annotation.PreAuthorize;
import com.xique.system.bean.domain.ParkInfo;
import com.xique.system.bean.domain.SystemRole;
import com.xique.system.bean.domain.SystemUser;
import com.xique.system.bean.domain.SystemUserRole;
import com.xique.system.bean.search.ParkInfoSearch;
import com.xique.system.service.service.ILoginPageService;
import com.xique.system.service.service.IParkInfoService;
import com.xique.system.service.service.ISystemRoleService;
import com.xique.system.service.service.ISystemUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author shd
 * @create 2021/11/11 14:58
 */
@RestController
@RequestMapping("/role")
public class SystemRoleController extends BaseController {

    @Autowired
    private ISystemRoleService roleService;

    @Autowired
    private ISystemUserService userService;

    @Autowired
    private IParkInfoService parkInfoService;

    @PreAuthorize(hasPermi = "system:role:list")
    @GetMapping("/list")
    public TableDataInfo list(SystemRole role)
    {
        Long userId = SecurityUtils.getUserId();
        if (!SecurityUtils.isAdmin(userId)) {
            if (UserConstants.Platform.ADMIN.equals(SecurityUtils.getPlatformType())) {
                role.setRoleType(UserConstants.UserType.MANAGER);
            }
            if (UserConstants.Platform.ADMIN_SERVICE.equals(SecurityUtils.getPlatformType())) {
                role.setRoleType(UserConstants.UserType.SERVICE_MANAGER);
            }
            if (UserConstants.Platform.ADMIN_PROJECT.equals(SecurityUtils.getPlatformType())) {
                role.setRoleType(UserConstants.UserType.PROJECT_MANAGER);
                role.setParkId(SecurityUtils.getParkId());
            }
        }
        startPage();
        List<SystemRole> list = roleService.selectRoleListV1(role);
        return getDataTable(list);
    }

    /**
     * 根据角色编号获取详细信息
     */
    @PreAuthorize(hasPermi = "system:role:query")
    @GetMapping(value = "/{roleId}")
    public AjaxResult getInfo(@PathVariable Long roleId)
    {
        return AjaxResult.success(roleService.selectRoleById(roleId));
    }

    /**
     * 新增角色
     */
    @PreAuthorize(hasPermi = "system:role:add")
    @Log(title = "角色管理", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@Validated @RequestBody SystemRole role)
    {
        role.setRoleKey(role.getRoleName());
        if (UserConstants.NOT_UNIQUE.equals(roleService.checkRoleNameUnique(role)))
        {
            return AjaxResult.error("新增角色'" + role.getRoleName() + "'失败，角色名称已存在");
        }
        else if (UserConstants.NOT_UNIQUE.equals(roleService.checkRoleKeyUnique(role)))
        {
            return AjaxResult.error("新增角色'" + role.getRoleName() + "'失败，角色权限已存在");
        }
        role.setDataScope("4");
        role.setCreateBy(SecurityUtils.getUsername());
        if (UserConstants.Platform.ADMIN.equals(SecurityUtils.getPlatformType())) {
            role.setRoleType(UserConstants.UserType.MANAGER);
        }
        if (UserConstants.Platform.ADMIN_SERVICE.equals(SecurityUtils.getPlatformType())) {
            role.setRoleType(UserConstants.UserType.SERVICE_MANAGER);
        }
        if (UserConstants.Platform.ADMIN_PROJECT.equals(SecurityUtils.getPlatformType())) {
            role.setRoleType(UserConstants.UserType.PROJECT_MANAGER);
            role.setParkId(SecurityUtils.getParkId());
            ParkInfo parkInfo = parkInfoService.selectParkInfoById(SecurityUtils.getParkId());
            role.setDeptId(parkInfo.getDeptId());
        }
        return toAjax(roleService.insertRole(role));

    }

    /**
     * 修改保存角色
     */
    @PreAuthorize(hasPermi = "system:role:edit")
    @Log(title = "角色管理", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@Validated @RequestBody SystemRole role)
    {
        roleService.checkRoleAllowed(role);
        if (UserConstants.NOT_UNIQUE.equals(roleService.checkRoleNameUnique(role)))
        {
            return AjaxResult.error("修改角色'" + role.getRoleName() + "'失败，角色名称已存在");
        }
        else if (UserConstants.NOT_UNIQUE.equals(roleService.checkRoleKeyUnique(role)))
        {
            return AjaxResult.error("修改角色'" + role.getRoleName() + "'失败，角色权限已存在");
        }
        role.setUpdateBy(SecurityUtils.getUsername());
        return toAjax(roleService.updateRole(role));
    }

    /**
     * 修改保存数据权限
     */
    @PreAuthorize(hasPermi = "system:role:edit")
    @Log(title = "角色管理", businessType = BusinessType.UPDATE)
    @PutMapping("/dataScope")
    public AjaxResult dataScope(@RequestBody SystemRole role)
    {
        roleService.checkRoleAllowed(role);
        return toAjax(roleService.authDataScope(role));
    }

    /**
     * 状态修改
     */
    @PreAuthorize(hasPermi = "system:role:edit")
    @Log(title = "角色管理", businessType = BusinessType.UPDATE)
    @PutMapping("/changeStatus")
    public AjaxResult changeStatus(@RequestBody SystemRole role)
    {
        roleService.checkRoleAllowed(role);
        role.setUpdateBy(SecurityUtils.getUsername());
        return toAjax(roleService.updateRoleStatus(role));
    }

    /**
     * 删除角色
     */
    @PreAuthorize(hasPermi = "system:role:remove")
    @Log(title = "角色管理", businessType = BusinessType.DELETE)
    @DeleteMapping("/{roleIds}")
    public AjaxResult remove(@PathVariable Long[] roleIds)
    {
        return toAjax(roleService.deleteRoleByIds(roleIds));
    }

    /**
     * 获取角色选择框列表
     */
    @PreAuthorize(hasPermi = "system:role:query")
    @GetMapping("/optionselect")
    public AjaxResult optionselect()
    {
        return AjaxResult.success(roleService.selectRoleAll());
    }
    /**
     * 查询已分配用户角色列表
     */
    @PreAuthorize(hasPermi = "system:role:list")
    @GetMapping("/authUser/allocatedList")
    public TableDataInfo allocatedList(SystemUser user)
    {
        user.setParkId(SecurityUtils.getParkId());
        startPage();
        List<SystemUser> list = userService.selectAllocatedList(user);
        return getDataTable(list);
    }

    /**
     * 查询未分配用户角色列表
     */
    @PreAuthorize(hasPermi = "system:role:list")
    @GetMapping("/authUser/unallocatedList")
    public TableDataInfo unallocatedList(SystemUser user)
    {
        user.setParkId(SecurityUtils.getParkId());
        startPage();
        List<SystemUser> list = userService.selectUnallocatedList(user);
        return getDataTable(list);
    }

    /**
     * 取消授权用户
     */
    @PreAuthorize(hasPermi = "system:role:edit")
    @Log(title = "角色管理", businessType = BusinessType.GRANT)
    @PutMapping("/authUser/cancel")
    public AjaxResult cancelAuthUser(@RequestBody SystemUserRole userRole)
    {
        return toAjax(roleService.deleteAuthUser(userRole));
    }

    /**
     * 批量取消授权用户
     */
    @PreAuthorize(hasPermi = "system:role:edit")
    @Log(title = "角色管理", businessType = BusinessType.GRANT)
    @PutMapping("/authUser/cancelAll")
    public AjaxResult cancelAuthUserAll(Long roleId, Long[] userIds)
    {
        return toAjax(roleService.deleteAuthUsers(roleId, userIds));
    }

    /**
     * 批量选择用户授权
     */
    @PreAuthorize(hasPermi = "system:role:edit")
    @Log(title = "角色管理", businessType = BusinessType.GRANT)
    @PutMapping("/authUser/selectAll")
    public AjaxResult selectAuthUserAll(Long roleId, Long[] userIds)
    {
        return toAjax(roleService.insertAuthUsers(roleId, userIds));
    }

    @GetMapping("/updateRoleParkId")
    public AjaxResult updateRoleParkId() {
        ParkInfoSearch parkInfoSearch = new ParkInfoSearch();
        List<ParkInfo> parkInfos = parkInfoService.selectParkInfoListBySearch(parkInfoSearch);
        List<SystemRole> systemRoles = roleService.selectRoleList(new SystemRole());
        List<SystemRole> needUpdateList = new ArrayList<>();
        for (SystemRole systemRole : systemRoles) {
            if (systemRole!=null && systemRole.getParkCode()!=null){
                ParkInfo parkInfo = parkInfos.stream().filter(e -> e.getCode().equals(systemRole.getParkCode())).findAny().orElse(null);
                if (parkInfo!=null){
                    systemRole.setParkId(parkInfo.getId());
                    needUpdateList.add(systemRole);
                }
            }
        }
        roleService.batchUpdateRole(needUpdateList);
        return AjaxResult.success();
    }
}
